package com.neusoft.nepm.controller;

import com.neusoft.nepm.utils.SendEmail;
import com.neusoft.nepm.vo.Captcha;
import com.neusoft.nepm.vo.ResponseData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * @author zouran
 * createDate：2023/6/20  23:04
 */
@RestController
@RequestMapping("/logon")
@Api(tags = "邮箱验证接口")
public class EmailController {
    private final SendEmail sendEmail;
    //验证码最小值
    private static final Integer minCaptcha =100000;
    //验证码最大值
    private static final Integer maxCaptcha =1000000;
    //验证码发送的时间差
    private static final Integer interval=1;
    //验证码有效期
    private static final Integer validity=5;
    //存放所有验证码
    private final Map<String, Captcha> captchaMap =new HashMap<>();
    public EmailController(SendEmail sendEmail) {
        this.sendEmail = sendEmail;
    }

    /**
     * 获取验证码
     * @param email 用户唯一账号识别（手机号码或者邮箱等）
     */
    @RequestMapping("/captcha")
    @ApiOperation(value = "发送验证码")
    public ResponseData<Object> sendCaptcha(@RequestParam("email") String email){
        ResponseData<Object> responseData=new ResponseData<>();
        if(isValidEmail(email))
        if(captchaMap.containsKey(email)&& captchaMap.get(email).isValid()) {
            responseData.setCode(1001);
            responseData.setMessage("验证码请求过于频繁!");
            return responseData;
        }
        Random random=new Random();
        Integer value=random.nextInt(maxCaptcha)%(maxCaptcha - minCaptcha)+ minCaptcha;
        //发送邮箱
        if(!sendEmail.send(email,sendEmail.logonContent(String.valueOf(value)), SendEmail.TITLE_LOGON)) {
            responseData.setCode(500);
            responseData.setMessage("验证码发送失败!");
            return responseData;
        }
        Captcha captcha=new Captcha(value,true);
        captchaMap.put(email,captcha);
        ScheduledExecutorService schedule= Executors.newScheduledThreadPool(1);
        schedule.schedule(() -> captchaMap.get(email).setValid(false),interval, TimeUnit.MINUTES);
        schedule.schedule(()->{
            captchaMap.remove(email);
        },validity,TimeUnit.MINUTES);
        System.out.println(captcha.getValue());
        responseData.setCode(200);
        responseData.setMessage("发送成功");
        return responseData;
    }
    /**
     * 检验验证码
     * @param captcha 验证码
     * @param email 用户的邮箱
     */
    @RequestMapping("/cheekCaptcha")
    @ApiOperation(value = "验证验证码")
    public ResponseData<Object> cheekCaptcha(@RequestParam("captcha") String captcha,@RequestParam("email") String email){
        ResponseData<Object> responseData=new ResponseData<>();
        if(captchaMap.containsKey(email)){
            if (Objects.equals(String.valueOf(captchaMap.get(email).getValue()), captcha)){
                 /*
                  执行注册成功后操作
                  */
                sendEmail.send(email,sendEmail.loginSuccessContent(),SendEmail.TITLE_LOGON_SUCCESS);
                responseData.setCode(200);
                responseData.setMessage("验证成功");
            }
            else {
                responseData.setCode(1001);
                responseData.setMessage("验证码错误!");
            }
        }else {
            responseData.setCode(1002);
            responseData.setMessage("验证码失效");
        }
        return responseData;
    }

    /**
     * @param email 邮箱
     * @return 是否合法
     */
    private boolean isValidEmail(String email) {
        if ((email != null) && (!email.isEmpty())) {
            return Pattern.matches("^(\\w+([-.][A-Za-z0-9]+)*){3,18}@\\w+([-.][A-Za-z0-9]+)*\\.\\w+([-.][A-Za-z0-9]+)*$", email);
        }
        return false;
    }

}
